﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Interactivity;
using System.Collections;
using System.Collections.Generic;
using System.Windows.Data;
using System.Linq;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Windows.Markup;
namespace Phone.Framework.Behaviors
{
    [ContentProperty("Items")]
    public class ApplicationBarSelectorBehavior : Behavior<PhoneApplicationPage>
    {

        public ApplicationBarSelectorBehavior()
        {
            Items = new ApplicationBarSelectorCollection();
        }

        protected override void OnAttached()
        {
            AssociatedObject.Loaded += new RoutedEventHandler(AssociatedObject_Loaded);
            base.OnAttached();
        }

        void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrEmpty(Pivot))
            {
                _pivotControl = this.AssociatedObject.FindName(Pivot) as Pivot;
                _pivotControl.SelectionChanged += new SelectionChangedEventHandler(Pivot_SelectionChanged);
            }

            this.AssociatedObject.Loaded -= new RoutedEventHandler(AssociatedObject_Loaded);
        }

        public ApplicationBarSelectorCollection Items { get; set; }

        public string Pivot { get; set; }

        private Pivot _pivotControl;

        void Pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            AssociatedObject.ApplicationBar.Buttons.Clear();
            var btns = Items[_pivotControl.SelectedIndex].Buttons;
            foreach (var item in btns)
            {
                AssociatedObject.ApplicationBar.Buttons.Add(item);
            }
        }
    }

    public class ApplicationBarSelectorCollection:System.Collections.ObjectModel.Collection<ApplicationBarSelector>
    {
    }

    public class ApplicationBarSelector
    {
        public ApplicationBarSelector()
        {
            _buttons = new List<IApplicationBarIconButton>();
        }

        private IList _buttons;
        public IList Buttons { get { return _buttons; } }

    }
}
